package com.glidebitmappool;

import com.glidebitmappool.internal.BitmapPool;
import com.glidebitmappool.internal.LruBitmapPool;

import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;

import java.util.Set;

/**
 * 位图池初基类
 *
 * @author renpengfei
 * @since 2021-03-12
 * Description: 位图池初基类
 */
public class GlideBitmapPool {
    private static final int DEFAULT_MAX_SIZE = 6 * 1024 * 1024;
    private static GlideBitmapPool sInstance;
    private BitmapPool bitmapPool;

    /**
     * 构造
     *
     * @param maxSize
     */
    private GlideBitmapPool(int maxSize) {
        // 原库  api大于等于11使用
        bitmapPool = new LruBitmapPool(maxSize);
    }

    /**
     * 构造
     *
     * @param maxSize
     * @param allowedConfigs
     */
    private GlideBitmapPool(int maxSize, Set<PixelFormat> allowedConfigs) {
        // 原库 api大于等于11使用
        bitmapPool = new LruBitmapPool(maxSize, allowedConfigs);
    }

    /**
     * 初始化
     *
     * @return GlideBitmapPool
     */
    private static GlideBitmapPool getInstance() {
        if (sInstance == null) {
            sInstance = new GlideBitmapPool(DEFAULT_MAX_SIZE);
        }
        return sInstance;
    }

    /**
     * 初始化
     *
     * @param maxSize
     */
    public static void initialize(int maxSize) {
        sInstance = new GlideBitmapPool(maxSize);
    }

    /**
     * 初始化
     *
     * @param maxSize
     * @param allowedConfigs
     */
    public static void initialize(int maxSize, Set<PixelFormat> allowedConfigs) {
        sInstance = new GlideBitmapPool(maxSize, allowedConfigs);
    }

    /**
     * 添加位图
     *
     * @param bitmap
     */
    public static void putBitmap(PixelMap bitmap) {
        getInstance().bitmapPool.put(bitmap);
    }

    /**
     * 获取位图
     *
     * @param width
     * @param height
     * @param config
     * @return PixelMap
     */
    public static PixelMap getBitmap(int width, int height, PixelFormat config) {
        return getInstance().bitmapPool.get(width, height, config);
    }

    /**
     * 获取位图
     *
     * @param width
     * @param height
     * @param config
     * @return PixelMap
     */
    public static PixelMap getDirtyBitmap(int width, int height, PixelFormat config) {
        return getInstance().bitmapPool.getDirty(width, height, config);
    }

    /**
     * 清除缓存
     */
    public static void clearMemory() {
        getInstance().bitmapPool.clearMemory();
    }

    /**
     * 清除部分缓存
     *
     * @param level
     */
    public static void trimMemory(int level) {
        getInstance().bitmapPool.trimMemory(level);
    }

    /**
     * 关闭位图池
     */
    public static void shutDown() {
        if (sInstance != null) {
            sInstance.bitmapPool.clearMemory();
            sInstance = null;
        }
    }
}
